﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraNavBar;
using DevExpress.XtraTreeList;
using MM.Commmon.UI;
using MM.Common.Base;
using MM.Common.DBBase;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MM.Common.Support
{
    public partial class FrmGeneralDicSetupCenter : FrmFunctionBase
    {
        public FrmGeneralDicSetupCenter()
        {
            InitializeComponent();
            this.centerFlag = ConfigFunction.GetSystemConfig("CENTERFLAG", "Y", "区域中心使用标志", "C");
        }

        private void btnSel_Click(object sender, EventArgs e)
        {
            this.FreshTable("");
        }
        private void EditItem(int id)
        {
            if (string.IsNullOrEmpty(this.dictCode))
            {
                XtraMessageBox.Show("请选择您要新增字段的表！");
            }
            else if (this.centerFlag == "Y")
            {
                FrmGeneralDicItemSetupCenter center = new FrmGeneralDicItemSetupCenter(this.dictCode, this.dictName, id);
                if (center.ShowDialog() == DialogResult.OK)
                {
                    if (id < 0)
                    {
                        id = center.DictionaryID;
                    }
                    this.FreshItem(id);
                }
                center.Dispose();
            }
            else
            {
                FrmGeneralDictionaryItemSetup setup = new FrmGeneralDictionaryItemSetup(this.dictCode, this.dictName, id);
                if (setup.ShowDialog() == DialogResult.OK)
                {
                    if (id < 0)
                    {
                        id = setup.DictionaryID;
                    }
                    this.FreshItem(id);
                }
                setup.Dispose();
            }
        }

        private void EditTable(string dict_type)
        {
            FrmGeneralDictionaryTableSetup setup = new FrmGeneralDictionaryTableSetup(base.FunctionParameter, dict_type);
            if (setup.ShowDialog() == DialogResult.OK)
            {
                this.FreshTable(setup.TableCode);
            }
            setup.Dispose();
        }

        private void FreshItem(int id)
        {
            string commandtext = "SELECT A.DT_ID,A.DT_TYPE,A.DT_NAME,A.DT_CODE,A.DT_PARENT_ID,A.DT_IS_LEAF,A.DT_SORT,A.INPUTCODE1,A.INPUTCODE2,A.DT_ZCODE,A.DT_USE,A.DT_DEFAULT_IS,D.DT_NAME AS DIC_FLAGNAME,(SELECT ORG_NAME FROM KTSYS_ORGANIZATION C WHERE C.ORG_CODE=B.ORG_CODE) ORG_NAME FROM MXHLY_SYS_DICTIONARY A,KTSYS_DICTIONARY_LOG B ";
            commandtext = commandtext + " LEFT JOIN MXHLY_SYS_DICTIONARY D ON D.DT_TYPE='DIC_FLAG' AND B.DIC_FLAG=D.DT_CODE WHERE A.DT_ID=B.DT_ID AND A.DT_TYPE = :tab  ORDER BY DT_SORT ,DT_CODE";
            DataParamCol parm = new DataParamCol(new DataParam[] { new InputDataParam("tab", this.dictCode) });
            DataTable dt = new DataTable();
            if (SystemInfo.DbData.Retrieve(commandtext, parm, ref dt))
            {
                this.treeDictionary.ClearNodes();
                this.treeDictionary.DataSource = dt;
                if (id > 0)
                {
                    for (int i = 0; i < this.treeDictionary.Nodes.Count; i++)
                    {
                        if (id.ToString() == this.treeDictionary.Nodes[i].GetValue("DT_ID").ToString())
                        {
                            this.treeDictionary.FocusedNode = this.treeDictionary.Nodes[i];
                            return;
                        }
                    }
                }
            }
        }

        private void FreshTable(string default_code)
        {
            string commandtext = "SELECT * FROM MXHLY_SYS_DICTIONARY_TABLE  WHERE 1=1 ";
            DataParamCol parm = new DataParamCol();
            if (this.scmbManageOrg.FieldValue != null)
            {
                commandtext = commandtext + " AND DT_TB_TABLE_CODE IN(SELECT DT_TYPE FROM MXHLY_SYS_DICTIONARY A,KTSYS_DICTIONARY_LOG B WHERE A.DT_ID=B.DT_ID AND B.ORG_CODE = :orgCode)";
                parm.Add(new InputDataParam("orgCode", this.scmbManageOrg.FieldValue.ToString()));
            }
            if (this.scmbFlag.FieldValue != null)
            {
                commandtext = commandtext + " AND DT_TB_TABLE_CODE IN(SELECT DT_TYPE FROM MXHLY_SYS_DICTIONARY A,KTSYS_DICTIONARY_LOG B WHERE A.DT_ID=B.DT_ID AND B.DIC_FLAG = :dicFlag)";
                parm.Add(new InputDataParam("dicFlag", this.scmbFlag.FieldValue.ToString()));
            }
            if (this.scmbGroup.FieldValue != null)
            {
                commandtext = commandtext + " AND DT_TB_GROUP = :groupCode";
                parm.Add(new InputDataParam("groupCode", this.scmbGroup.FieldValue.ToString()));
            }
            commandtext = commandtext + " ORDER BY DT_TB_DESC ,DT_TB_TABLE_CODE";
            DataTable dt = new DataTable();
            if (SystemInfo.DbData.Retrieve(commandtext, parm, ref dt))
            {
                this.GridDicList.DataSource = dt;
            }
            if (!string.IsNullOrEmpty(default_code))
            {
                int dataSourceIndex = -1;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i]["DT_TB_TABLE_CODE"].ToString() == default_code)
                    {
                        dataSourceIndex = i;
                        break;
                    }
                }
                this.GridViewDicList.FocusedRowHandle = this.GridViewDicList.GetRowHandle(dataSourceIndex);
            }
        }

        private void FrmGeneralDicSetupCenter_Load(object sender, EventArgs e)
        {
            this.DicFlagList = GetDicFlagDic();
            this.scmbDicFlag.Items.Clear();
            foreach (KeyValuePair<string, string> pair in this.DicFlagList)
            {
                this.scmbDicFlag.Items.Add(pair.Key);
            }
        }

        private static Dictionary<string, string> GetDicFlagDic()
        {
            string commandtext = "SELECT DT_NAME,DT_CODE FROM MXHLY_SYS_DICTIONARY WHERE DT_USE='Y' AND DT_TYPE = 'DIC_FLAG'";
            DataTable dt = new DataTable();
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            SystemInfo.DbData.Retrieve(commandtext, ref dt);
            foreach (DataRow row in dt.Select())
            {
                dictionary.Add(row["DT_NAME"].ToString(), row["DT_CODE"].ToString());
            }
            return dictionary;
        }

        private void GridViewDicList_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            DataRow focusedDataRow = this.GridViewDicList.GetFocusedDataRow();
            if (focusedDataRow != null)
            {
                string str = focusedDataRow["DT_TB_TABLE_CODE"].ToString();
                string str2 = focusedDataRow["DT_TB_DISPLAY_NAME"].ToString();
                focusedDataRow["DT_TB_MODIFY"].ToString();
                this.dictCode = str;
                this.dictName = str2;
                this.FreshItem(-1);
            }
        }

        public override bool Init()
        {
            if (SystemInfo.DbData.IsOpen)
            {
                this.scmbFlag.FieldValue = GeneralDictionary.GetDictDefaultValue("DIC_FLAG");
                this.FreshTable("");
            }
            return base.Init();
        }

        private void navBarItem1_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
        }

        private void nbiDelete_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            if ((this.treeDictionary.FocusedNode.GetDisplayText("DIC_FLAGNAME") != null) && (this.treeDictionary.FocusedNode.GetDisplayText("DIC_FLAGNAME").ToString() == "通过"))
            {
                XtraMessageBox.Show("已经通过审核,不能删除！", "提示");
            }
            else if (XtraMessageBox.Show("是否真的删除?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                GeneralDictionary.DeleteDict(this.treeDictionary.FocusedNode.GetDisplayText("DT_ID").Trim());
                this.FreshItem(-1);
            }
        }

        private void nbiDeleteTable_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            if (this.treeDictionary.Nodes.Count > 0)
            {
                XtraMessageBox.Show("还有项目不能删除表！", "提示");
            }
            else if (XtraMessageBox.Show("是否真的删除?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                GeneralDictionary.DeleteTableDict(this.dictCode);
                this.FreshTable("");
            }
        }

        private void nbiEdit_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            string str = this.treeDictionary.FocusedNode.GetDisplayText("DT_ID").Trim();
            if (str.IsInt())
            {
                this.EditItem(int.Parse(str));
            }
        }

        private void nbiEditTable_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            this.EditTable(this.dictCode);
        }

        private void nbiNew_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            this.EditItem(-1);
        }

        private void nbiNewTable_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            this.EditTable(null);
        }

        private void nbiPrint_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            for (int i = 0; i < this.treeDictionary.Nodes.Count; i++)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("UPDATE KTSYS_DICTIONARY_LOG SET ");
                builder.Append(" CHECK_TIME = sysdate,CHECK_EMP_ID = :checkEmpId,DIC_FLAG =:dicFlag");
                builder.Append(" WHERE DT_ID = :dtId");
                DataParamCol parms = new DataParamCol(new DataParam[] { new InputDataParam("checkEmpId", SystemInfo.OperId), new InputDataParam("dicFlag", this.DicFlagList[this.treeDictionary.Nodes[i].GetValue("DIC_FLAGNAME").ToString()]), new InputDataParam("dtId", this.treeDictionary.Nodes[i].GetValue("DT_ID").ToString()) });
                SystemInfo.DbData.ExecuteSql(builder.ToString(), parms);
            }
            MessageBox.Show("审核完毕！", "审核提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }

        private void ShowHitInfo(TreeListHitInfo hi)
        {
            if (hi.Node != null)
            {
                this.checkNode = hi.Node.GetValue("DT_ID").ToString();
            }
        }

        private void treeDictionary_DoubleClick(object sender, EventArgs e)
        {
            string str = this.treeDictionary.FocusedNode.GetDisplayText("DT_ID").Trim();
            if (str.IsInt())
            {
                this.EditItem(int.Parse(str));
            }
        }

        private void treeDictionary_MouseDown(object sender, MouseEventArgs e)
        {
            this.ShowHitInfo(this.treeDictionary.CalcHitInfo(new Point(e.X, e.Y)));
        }
    }
}
